package com.itheima.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/*
    JDBC工具类
 */
public class JDBCUtils {

    private static Connection connection;

    //1.私有构造方法
    private JDBCUtils() {
    }
    //2.声明配置信息变量


    private static String driverClass;

    private static String url;

    private static String username;

    private static String password;

    //3.静态代码块中实现加载配置文件和注册驱动
    static {
        //通过类加载器返回配置文件的字节流
        InputStream resourceAsStream = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties prop = new Properties();
        try {
            //创建Properties集合，加载流对象的信息
            prop.load(resourceAsStream);
            //获取信息为变量赋值
            driverClass = prop.getProperty("driverClass");
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");
            //注册驱动
            Class.forName(driverClass);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //4.获取数据库连接的方法
    public static Connection getConnect() {
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //5.释放资源的方法
    public static void close(Connection connection, Statement statement, ResultSet resultset) {
        try {
            if (connection!=null){
                connection.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (statement!=null){
                statement.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (resultset!=null){
                resultset.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void close (Connection connection, Statement statement){
        close(connection,statement,null);
    }
}